package com.community.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.community.dto.GiteeUser;
import com.community.dto.TokenDTO;
import okhttp3.*;
import org.springframework.stereotype.Component;


import java.io.IOException;

/**
 * @author 赵德胤
 * @create 2020-05-31-23:55
 *
 * provider 提供者
 *
 **/
@Component
public class GiteeProvider {

    public String getToken(TokenDTO tokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(tokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token")
                .post(body)
                .build();


        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            System.out.println(string);
            JSONObject jsonObject = JSON.parseObject(string);
            String access_token = (String) jsonObject.get("access_token");
            System.out.println(access_token);
            return access_token;
        } catch (IOException e) {
        }
        return null;
    }

    public GiteeUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
            return giteeUser;
        } catch (IOException e) {
        }
        return null;
    }
}
